package com.attendance.www.hr.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.RetroactiveBean;
import com.attendance.www.hr.beans.RetroactiveTimesBean;
import com.attendance.www.hr.dao.mapper.AttendanceMapper;
import com.attendance.www.hr.dao.mapper.RetroactiveTimesMapper;
import com.attendance.www.hr.entitys.Attendance;
import com.attendance.www.hr.entitys.RetroactiveTimes;
import com.attendance.www.hr.entitys.RetroactiveTimesExample;
import com.attendance.www.hr.entitys.RetroactiveTimesExample.Criteria;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.IRetroactiveService;
import com.attendance.www.hr.service.IRetroactiveTimesService;

/**
 * 补签次数设置
 * @author zx
 */
@Service
public class RetroactiveTimesServiceImpl implements IRetroactiveTimesService {

	@Resource
	private RetroactiveTimesMapper retroactiveTimesDao;
	@Resource
	private IRetroactiveService retroactiveService;
	@Resource
	private AttendanceMapper attendanceDao;
	
	/**
	 * 验证是否已有该开始日期（增and改）
	 * @param startDate
	 */
	private void checkDate(Date startDate, Integer retroactiveTimesId) {
		RetroactiveTimesExample rtExample=new RetroactiveTimesExample();
		Criteria criteria=rtExample.createCriteria();
        criteria.andStartDateEqualTo(startDate);
        if (retroactiveTimesId!=null) {
        	criteria.andRetroactiveTimesIdNotEqualTo(retroactiveTimesId);
		}
		List<RetroactiveTimes> rtList = retroactiveTimesDao.selectByExample(rtExample);
		if (rtList.size()>0) {
			throw new ResultFaultException("15_00001");
		}
	}
	
	/**
	 * 获取结束日期
	 * 如果插入以前的月份
	 * @param startDate
	 * @return
	 */
	private Date getEndDate(Date startDate, Integer retroactiveTimesId) {
		Calendar calendar = Calendar.getInstance();
		//有比设置月大的月份，--》调整本次设置的结束时间
        RetroactiveTimesExample rtExample = new RetroactiveTimesExample();
        Criteria criteria=rtExample.createCriteria();
        criteria.andStartDateGreaterThan(startDate);
        if (retroactiveTimesId!=null) {
        	criteria.andRetroactiveTimesIdNotEqualTo(retroactiveTimesId);
		}
        rtExample.setOrderByClause("start_date asc");
        List<RetroactiveTimes> rtList = retroactiveTimesDao.selectByExample(rtExample);
        
        Date endDate = null;
        
        if (rtList.size()>0) {//有比设置月大的月份
			RetroactiveTimes retroactiveTimesGreater = rtList.get(0);
			Date greaterStartDate = retroactiveTimesGreater.getStartDate();
			endDate = DateUtils.addDays(greaterStartDate, -1);
		} else {
			calendar.set(9999, 11, 31);
			endDate=calendar.getTime();
		}
        return endDate;
	}
	/**
	 * 增
	 */
	@Override
	public boolean saveRetroactiveTimes(RetroactiveTimesBean retroactiveTimesBean) {
		RetroactiveTimes rt = new RetroactiveTimes();
		int year = retroactiveTimesBean.getYear();
		int month = retroactiveTimesBean.getMonth();
		Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(year, month - 1, 1);//月份从0开始
        Date startDate=calendar.getTime();
        this.checkDate(startDate, null);
        //有比设置月小的月，--》更新其结束时间
        RetroactiveTimesExample rtExample1 = new RetroactiveTimesExample();
        rtExample1.createCriteria().andStartDateLessThan(startDate)
        .andEndDateGreaterThan(startDate);
        rtExample1.setOrderByClause("start_date desc");
        List<RetroactiveTimes> rtList1 = retroactiveTimesDao.selectByExample(rtExample1);
        if (rtList1.size()>0) {
        	RetroactiveTimes retroactiveTimesLess = new RetroactiveTimes();
        	retroactiveTimesLess.setRetroactiveTimesId(rtList1.get(0).getRetroactiveTimesId());
        	calendar.add(Calendar.DATE, -1);//上个月最后一天
        	retroactiveTimesLess.setEndDate(calendar.getTime());
        	
        	retroactiveTimesDao.updateByPrimaryKeySelective(retroactiveTimesLess);
        }
        
        Date endDate = this.getEndDate(startDate, null);
        
		rt.setEndDate(endDate);
		rt.setStartDate(startDate);
		rt.setTimes(retroactiveTimesBean.getTimes());
		
		int record = retroactiveTimesDao.insertSelective(rt);
		if (record<=0) {
			return false;
		}
		return true;
	}

	/**
	 * 删
	 */
	@Override
	public boolean deleteRetroactiveTimes(String retroactiveTimesIdStr) {
		retroactiveTimesDao.deleteByPrimaryKey(Integer.parseInt(retroactiveTimesIdStr));
		return true;
	}

	/**
	 * 改
	 */
	@Override
	public boolean updateRetroactiveTimes(RetroactiveTimesBean retroactiveTimesBean) {
		RetroactiveTimes rt = retroactiveTimesDao.selectByPrimaryKey(retroactiveTimesBean.getRetroactiveTimesId());
		int year = retroactiveTimesBean.getYear();
		int month = retroactiveTimesBean.getMonth();
		Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(year, month-1, 1);
        Date startDate=calendar.getTime();
        if (!startDate.equals(rt.getStartDate())) {
        	this.checkDate(startDate, rt.getRetroactiveTimesId());
        	rt.setStartDate(startDate);
        	Date endDate = this.getEndDate(startDate, rt.getRetroactiveTimesId());
        	rt.setEndDate(endDate);
		}
        //清空两个时间
        rt.setCreateTime(null);
        rt.setUpdateTime(null);
        rt.setTimes(retroactiveTimesBean.getTimes());
		retroactiveTimesDao.updateByPrimaryKeySelective(rt);
		return true;
	}

	/**
	 * 查
	 */
	@Override
	public List<RetroactiveTimesBean> getRetroactiveTimesList() {
		Calendar calendar = Calendar.getInstance();
		List<RetroactiveTimesBean> rtBeanList = new ArrayList<>();
		RetroactiveTimesExample rtExample = new RetroactiveTimesExample();
		rtExample.setOrderByClause("start_date");
		List<RetroactiveTimes> rtList = retroactiveTimesDao.selectByExample(rtExample);
		for (RetroactiveTimes retroactiveTimes : rtList) {
			Date startDate = retroactiveTimes.getStartDate();
			calendar.setTime(startDate);
			
			RetroactiveTimesBean rtBean = new RetroactiveTimesBean();
			rtBean.setCreateTime(retroactiveTimes.getCreateTime());
			rtBean.setEndDate(retroactiveTimes.getEndDate());
			rtBean.setRetroactiveTimesId(retroactiveTimes.getRetroactiveTimesId());
			rtBean.setStartDate(startDate);
			rtBean.setTimes(retroactiveTimes.getTimes());
			rtBean.setUpdateTime(retroactiveTimes.getUpdateTime());
			rtBean.setYear(calendar.get(Calendar.YEAR));
			rtBean.setMonth(calendar.get(Calendar.MONTH) + 1);
			rtBeanList.add(rtBean);
		}
		return rtBeanList;
	}

	/**
	 * 查询某时间是否可以补签
	 */
	@Override
	public boolean getIsAbleRetroactive(RetroactiveBean retroactiveBean) {
		// TODO Auto-generated method stub
		Date retroactiveDate = retroactiveBean.getAttendanceDate();
		if (retroactiveDate == null) {
			Attendance att = attendanceDao.selectByPrimaryKey(retroactiveBean.getAttendanceId());
			retroactiveDate = att.getAttendanceDate();
		}
		RetroactiveTimesExample rtExample = new RetroactiveTimesExample();
		rtExample.createCriteria().andStartDateLessThanOrEqualTo(retroactiveDate)
		.andEndDateGreaterThanOrEqualTo(retroactiveDate);
		List<RetroactiveTimes> rtList = retroactiveTimesDao.selectByExample(rtExample);
		if (rtList.size()>0) {
			int times = rtList.get(0).getTimes();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(retroactiveDate);
			calendar.set(Calendar.DAY_OF_MONTH, 1);
			Date startDate=calendar.getTime();
			calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));//一个月最后一天
			Date endDate=calendar.getTime();
			int rNum = retroactiveService.getRetroactiveNumAble(retroactiveBean.getEmployeeId(), startDate, endDate);
			if (rNum >= times) {
				List<String> errorMsgList = new ArrayList<String>();// 创建错误信息列表
				String errStr = "本月补签次数上限为：" + times + "次。";
				errorMsgList.add(errStr);
				throw new ResultFaultException("15_00002", errorMsgList);
			}
		}
		return true;
	}

}
